package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {

    @Resource
    private DeptServiceImpl deptService;

    @Resource
    private EmpExprServiceImpl empExprService;

    @Override
    public PageResult<Emp> getPage(EmpQueryParam param) {
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        // 根据最后修改时间倒序排序
        page.addOrder(OrderItem.asc("entry_date"));
        // 调用page方法完成分页查询
        page = page(page);

        // ↓↓↓为每个员工补齐 部门名称↓↓↓
        // 获取员工集合
        List<Emp> list = page.getRecords();
        // 获取所有员工的部门id
        Set<Integer> deptId = list.stream().map(emp -> emp.getDeptId()).collect(Collectors.toSet());
        // 批量查询这些部门的信息，并转换成Map<部门id, 部门名称>
        List<Dept> deptList = deptService.listByIds(deptId);
        Map<Integer, String> deptMap = deptList.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));

        // 将部门名称封装到员工对象中
        list.forEach(emp -> emp.setDeptName(deptMap.get(emp.getDeptId())));

        return new PageResult<>(page.getTotal(), list);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmp(Emp emp) {
        //新增员工基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        save(emp);

        //新增员工工作经历
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(empExpr -> empExpr.setEmpId(emp.getId()));
        empExprService.saveBatch(exprList);
    }
}
